var
// imports
http = require('http'),
url = require('url'),
fs = require('fs'),
qs = require('querystring'),

// constants
ENCODING = 'utf-8',
HTML = './assets/template.html',
CSS = './assets/template.css',
LIB = './assets/jquery.min.js',
JS = './assets/template.js',
MSG_FILE = '/messages.json',

// variable
dir = '../_locales/',

// functions
loadTemplate = function(resp, path, type) {
	resp.writeHead(200, { 'Content-Type' : type });
	fs.readFile(path, ENCODING, function(err, data) {
		!err && data && resp.write(data);
		resp.end();
	});
};

// http server
http.createServer(function(req, resp) {

	var path = url.parse(req.url, false, true).pathname;

	// read
	if (req.method == 'GET') {

		if (path == '/js') {
			loadTemplate(resp, JS, 'application/javascript');

		} else if (path == '/lib') {
			loadTemplate(resp, LIB, 'application/javascript');

		} else if (path == '/css') {
			loadTemplate(resp, CSS, 'text/css');

		} else if (path == '/config') {
			resp.writeHead(200, { 'Content-Type' : 'application/json' });
			resp.write(JSON.stringify({ path: dir }));
			resp.end();

		} else if (path == '/json') {
			resp.writeHead(200, { 'Content-Type' : 'application/json' });
			fs.readdir(dir, function(err, files) {
				var data = {};
				if (!err && files) {
					for (var i = 0; i < files.length; i++) {
						try {
							var file = dir + files[i] + MSG_FILE,
							value = fs.readFileSync(file, ENCODING) || '{}';
							data[files[i]] = JSON.parse(value);
						} catch (e) {
							console.log(e);
						}
					}
				}
				resp.write(JSON.stringify(data));
				resp.end();
			});

		} else {
			loadTemplate(resp, HTML, 'text/html');
		}

	// write
	} else if (req.method == 'POST' && path.length > 2) {
		var data = '';
		resp.writeHead(200, { 'Content-Type' : 'text/plain' });
		req.addListener('data', function(chunk) {
			data += chunk;
		});
		req.addListener('end', function() {
			data = qs.parse(data);
			if (path == '/config') {
				dir = data.path + '/';
				resp.end();
			} else {
				var file = dir + path.substring(1) + MSG_FILE,
				nData = {};
				for (var key in data) {
					var entry = {},
					msg = data[key].split('$');
					if (msg.length > 1) { // may has placeholder
						var placeholders = {},
						count = 0;
						for (var i = 1; i < msg.length; i += 2) {
							if (/^[\w\d@]+$/.test(msg[i])) {
								placeholders[msg[i].toUpperCase()] = {
									content: '$' + (++count)
								};
							}
						}
						if (count > 0) {
							entry.placeholders = placeholders;
						}
					}
					entry.message = data[key];
					nData[key] = entry;
				}
				try {
					!fs.existsSync(dir) && fs.mkdirSync(dir);
					fs.mkdirSync(dir + path.substring(1));
				} catch (e) {
				}
				fs.writeFile(file, JSON.stringify(nData), ENCODING, function(err) {
					!err && resp.write('success');
					resp.end();
				});
			}
		});

	} else {
		resp.end();
	}
}).listen(2036);